package role

import (
	"context"
	"go-zero-project/services/user/rpc/internal/mapper"
	"go-zero-project/services/user/rpc/internal/mapper/bo"
	"go-zero-project/services/user/rpc/internal/svc"
	"go-zero-project/services/user/rpc/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type ListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRoleListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListLogic {
	return &ListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ListLogic) RoleList(in *pb.RoleListReq) (*pb.RoleListResp, error) {
	// 1.select count
	pageNum := in.PageNum
	pageSize := in.PageSize
	startPageIndex := 0
	if pageNum > 1 {
		startPageIndex = int((pageNum - 1) * pageSize)
	}
	sysRoleBO := bo.SysRoleBO{RoleNameLike: in.RoleName}
	roleMapper := mapper.NewRoleMapper()
	selectCount, err := roleMapper.SelectCount(l.svcCtx.DBEngin, sysRoleBO)
	if err != nil {
		logx.Errorf("select roleListCount failed:%s", err.Error())
		return nil, err
	}
	resp := &pb.RoleListResp{}
	resp.CurrentPage = pageNum
	resp.TotalPage = int32(selectCount)
	if selectCount <= 0 {
		return resp, nil
	}
	// 2.select List
	sysRoleBO.StartIndex = startPageIndex
	sysRoleBO.PageSize = int(pageSize)
	selectList, err := roleMapper.SelectList(l.svcCtx.DBEngin, sysRoleBO)
	if err != nil {
		logx.Errorf("select selectList failed:%s", err.Error())
		return nil, err
	}
	// 3.return obj
	var dataList []*pb.RoleInfoListResp
	for _, v := range selectList {
		dataList = append(dataList, &pb.RoleInfoListResp{
			RoleId:     v.RoleId,
			RoleName:   v.RoleName,
			Remark:     v.Remark,
			CreateTime: v.CreateTime.Format("2006-01-02 15:04:05"),
		})
	}
	resp.Data = dataList
	return resp, nil
}
